/**
 * @Project Name:hoofungson-elk-log
 * @Package Name:cn.hoofungson.framework.elk.log.util
 * @Since JDK 1.8
 */

package cn.hoofungson.framework.elk.log.util;

import cn.hoofungson.framework.elk.log.annotation.LogServiceContext;
import cn.hoofungson.framework.elk.log.monitor.MonitorLogger;
import cn.hoofungson.framework.elk.log.monitor.MonitorLoggerFactory;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 日志业务工具
 * @Author 胡松 hoofungson@163.com
 * @Date 2019-08-31 16:46
 * @Version V1.0
 */
@Slf4j
public class LogServiceUtils {

    private LogServiceUtils() {
    }

    /**
     * 入参状态码：200001
     **/
    private static final String INTERFACE_PARAM_CODE = "200001";

    /**
     * 处理切点
     *
     * @param joinPoint
     **/
    public static void handlerJoinPoint(JoinPoint joinPoint) {
        if (null == joinPoint) {
            return;
        }
        //获取sdk上下文
        LogServiceContext logServiceContext = ThreadLocalUtils.getLogServiceContextThreadLocal().get();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        Object[] args = joinPoint.getArgs();
        log.info("切入点实例:{}", joinPoint.getSignature().getDeclaringTypeName());
        //获取参数名称和值
        String[] parameterNames = methodSignature.getParameterNames();
        Map<String, String> logContext = new HashMap<>();
        if (null != parameterNames && parameterNames.length > 0) {
            for (int i = 0; i < parameterNames.length; i++) {
                logContext.put(parameterNames[i], args[i] != null ? args[i].toString() : "");
            }
        }
        if (null != logServiceContext) {
            //声明切入点监控日志
            MonitorLogger monitorLogger = MonitorLoggerFactory.getMonitorLogger(methodSignature.getDeclaringType());
            monitorLogger.info(INTERFACE_PARAM_CODE, "被调用方法入参输出......");
            monitorLogger.info(logServiceContext.code(), logServiceContext.note(), logContext);
        }
    }
}
